package com.kaisu.blog.infrastructure.user;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author kaisu
 */
@Getter
@Setter
@Entity
@ToString
@DynamicInsert
@DynamicUpdate
@Table(name = "`user`", uniqueConstraints = {
        @UniqueConstraint(name = "user_username_unique", columnNames = "username"),
        @UniqueConstraint(name = "user_phone_unique", columnNames = "phone"),
        @UniqueConstraint(name = "user_email_unique", columnNames = "email")
})
@NamedEntityGraph(
        name = "user-follow",
        attributeNodes = {
                @NamedAttributeNode(value = "followers"),
                @NamedAttributeNode(value = "followings")
        }
)
public class UserPO {
    /**
     * 主键
     */
    @Id
    private String id;
    /**
     * 头像
     */
    private String avatarId;
    /**
     * 昵称
     */
    private String nickname;
    /**
     * 用户名
     */
    @Column(unique = true)
    private String username;
    /**
     * 电话
     */
    @Column(unique = true)
    private String phone;
    /**
     * 邮箱
     */
    @Column(unique = true)
    private String email;
    /**
     * 密码
     */
    private String password;
    /**
     * 是否启用
     */
    private boolean enable;
    /**
     * 角色列表
     */
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "user_role",
            joinColumns = {
                    @JoinColumn(name = "user_id"),
            },
            inverseJoinColumns = {
                    @JoinColumn(name = "role_id")
            }
    )
    private Set<RolePO> roles;
    /**
     * 粉丝列表
     */
    @OneToMany(mappedBy = "following", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @ToString.Exclude
    private Set<FollowPO> followers;
    /**
     * 关注列表
     */
    @OneToMany(mappedBy = "follower", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @ToString.Exclude
    private Set<FollowPO> followings;
    /**
     * 创建时间
     */
    @CreationTimestamp
    private LocalDateTime createTime;
    /**
     * 更新时间
     */
    @UpdateTimestamp
    private LocalDateTime updateTime;
}